package com.jifeng.sterilizer.exception;

import com.jifeng.sterilizer.constant.BizCodeEnume;
import com.jifeng.sterilizer.utils.R;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.jifeng.sterilizer.controller")
public class ControllerAdviceExecption {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handValidException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            // 得到错误信息
            String message = item.getDefaultMessage();
            // 得到错误字段
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public R handNotReadableException(HttpMessageNotReadableException e){
        return R.error(400,"参数格式错误！");
    }

//    @ExceptionHandler(value = NullPointerException.class)
    public R handNullPointerException(NullPointerException e){
        return R.error(400,"参数值无效");
    }
}
